<script setup>
  import { onMounted, reactive, ref, computed, watch, nextTick } from 'vue';
  // 局部自定义指令
  // https://cn.vuejs.org/guide/reusability/custom-directives.html
  defineOptions({name: ''});
  const props = defineProps({});
  const emits = defineEmits(['on-ok']);
  onMounted(() => {});

  const spanValue = ref('');
  const suffixValue = ref('.exe')
  const copyValue = ref('');
  // 使用小驼峰命名法
  const vCopy = {
    created() {},
    beforeMount() {},
    // 加载
    mounted(el, binding) {
      copyValue.value = binding.value;
      el.addEventListener('click', function() {
        const suffix = el.getAttribute('copy-value-suffix');
        copyToClipboard(copyValue.value, suffix);
      });
    },
    beforeUpdate() {},
    // 更新
    updated(el, binding) {
      copyValue.value = binding.value;
    },
    // 卸载前
    beforeUnmount(el) {
      el.removeEventListener('click', function() {
        copyToClipboard();
      });
    },
    unmounted() {}
  }
  function copyToClipboard(text, suffix) {
    if(!text) {
      ElNotification.warning({
        message: '文本为空',
      })
      return;
    }
    try {
      navigator.clipboard.writeText(text + suffix)
        .then(function() {
          console.log(text.split('.'));
          ElNotification.success({
            title: '复制成功',
            message: '后缀名为' + suffix,
          })
        })
        .catch(function(err) {
          ElNotification.error({
            message: '复制失败',
          })
        });
    } catch (error) {
      ElNotification.warning({
        message: '当前浏览器不支持复制功能',
      })
    }
  }

  // 子组件暴露
  defineExpose({});
  
</script>

<template>
 <div>
    <el-input v-focus v-model="spanValue" style="width: 240px" placeholder="输入要复制的文本" />
    <el-input v-model="suffixValue" style="width: 100px" placeholder="输入要添加的后缀名" />
    <el-button type="primary" :copy-value-suffix="suffixValue" v-copy="spanValue">点击我进行复制</el-button>
  </div>
</template>

<style lang="less" scoped>
div {
  cursor: pointer;
}
</style>
